﻿/*
helferlein.com ( http://www.helferlein.com )
Michael Tobisch

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions 
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
using DotNetNuke.UI.UserControls;
using DotNetNuke.UI.WebControls;
using helferlein.DNN.Modules.Form.Business;
using helferlein.UI.WebControls.Validators;
using helferlein.DNN.Modules.BabelFish.Business;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Security.Permissions;
using System.Collections;

namespace helferlein.DNN.Modules.Form.UI
{
   partial class Form : PortalModuleBase, IActionable
   {
#region Optional Interfaces
      /// <summary>
      /// Implementation of the IActionable interface
      /// </summary>
      /// <remarks>
      /// Adds 2 Module Actions:
      /// 1. Add Form Item
      /// 2. Edit Submissions
      /// </remarks>
      public ModuleActionCollection ModuleActions
      {
         get
         {
            ModuleActionCollection actions = new ModuleActionCollection();
            // Add Form Item
            actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), ModuleActionType.AddContent, String.Empty, String.Empty, base.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
            // Edit Submissions
            actions.Add(GetNextActionID(), Localization.GetString("EditSubmissions.Text", LocalResourceFile), ModuleActionType.AddContent, String.Empty, String.Empty, base.EditUrl("EditSubmissions"), false, SecurityAccessLevel.Edit, true, false);
            return actions;
         }
      }
#endregion

#region Private Properties
      private FormItemController formItemController = null;
      private FormSubmissionController formSubmissionController = null;
      private List<FormSubmissionInfo> formSubmissions;
      private List<FormItemInfo> theForm;
      private bool hasRequiredValidators;
      private CaptchaControl formCaptcha = null;
      private Dictionary<string, string> _uploadedFiles = null;
      private bool sendCopy = false;
      private BabelFishController babelFishController;
      private DotNetNuke.Services.Tokens.TokenReplace tokenReplace = null;
      private Dictionary<string, string> _hostSettings = null;
      private PortalSettings _currentPortalSettings = null;
      private string _formValidationGroup;
      private string _uploadFolder = String.Empty;

      /// <summary>
      /// Singleton FormItemController object
      /// </summary>
      protected FormItemController FormItemController
      {
         get
         {
            if (formItemController == null)
               formItemController = new FormItemController();
            return formItemController;
         }
      }

      /// <summary>
      /// Singleton FormSubmissionController object
      /// </summary>
      protected FormSubmissionController FormSubmissionController
      {
         get
         {
            if (formSubmissionController == null)
               formSubmissionController = new FormSubmissionController();
            return formSubmissionController;
         }
      }

      protected Dictionary<string, string> HostSettings
      {
         get
         {
            if (_hostSettings == null)
               _hostSettings = HostController.Instance.GetSettingsDictionary();
            return _hostSettings;
         }
      }

      /// <summary>
      /// Generic List of FormItemInfo objects that define the form
      /// </summary>
      protected List<FormItemInfo> TheForm
      {
         get { return theForm; }
         set { theForm = value; }
      }

      /// <summary>
      /// Generic List of FormSubmissionInfo objects to be displayed
      /// </summary>
      protected List<FormSubmissionInfo> FormSubmissions
      {
         get
         {
            if (formSubmissions == null)
            {
               DateTime since = new DateTime();
               if (this.KeepDays == 0)
                  since = new DateTime(1800, 1, 1); /* Should be long enough... :-) */
               else
                  since = DateTime.Now.AddDays((-1) * this.KeepDays);
               formSubmissions = this.FormSubmissionController.GetPublic(base.ModuleId, since);
               if (base.Settings["GroupOutputBy"] != null)
               {
                  FormItemInfo fii = this.FormItemController.Get(Convert.ToInt32(Convert.ToString(base.Settings["GroupOutputBy"]).Substring(10)));
                  formSubmissions.Sort(new SubmissionComparer(fii.FormItemLabel));
               }
            }
            return formSubmissions;
         }
         set { formSubmissions = value; }
      }

      /// <summary>
      /// Value will be set during creation of the form to determine if an explanation of the required symbol has to be created or not
      /// </summary>
      protected bool HasRequiredValidators
      {
         get { return hasRequiredValidators; }
         set { hasRequiredValidators = value; }
      }

      /// <summary>
      /// Generic List of uploaded file names
      /// </summary>
      protected Dictionary<string, string> UploadedFiles
      {
         get
         {
            if (_uploadedFiles == null)
               _uploadedFiles = new Dictionary<string, string>();
            return _uploadedFiles;
         }
         set { _uploadedFiles = value; }
      }

      /// <summary>
      /// The send copy option will only be visible if the value of a EMailAddress form item is used as the sender address
      /// </summary>
      protected bool HideSendCopy
      {
         get
         {
            return ((!(Convert.ToBoolean(base.Settings["SubmitByEMail"]))) || (this.SenderAddress == "[ADMIN]") || (this.SenderAddress == "[HOST]") || (this.SenderAddress.StartsWith("[USERID]")));
         }
      }

      /// <summary>
      /// The maximum SortOrder value
      /// </summary>
      protected int MaxSortOrderValue
      {
         get
         {
            int i = 0;
            foreach (FormItemInfo fii in this.TheForm)
               i = Math.Max(i, fii.SortValue.Value);
            return i;
         }
      }

      protected BabelFishController BabelFishController
      {
         get
         {
            if (babelFishController == null)
               babelFishController = new BabelFishController();
            return babelFishController;
         }
      }

      protected DotNetNuke.Services.Tokens.TokenReplace TokenReplace
      {
         get
         {
            if (tokenReplace == null)
               tokenReplace = new DotNetNuke.Services.Tokens.TokenReplace();
            return tokenReplace;
         }
      }

      protected PortalSettings CurrentPortalSettings
      {
         get
         {
            if (_currentPortalSettings == null)
               _currentPortalSettings = PortalController.GetCurrentPortalSettings();
            return _currentPortalSettings;
         }
      }

      protected string FormValidationGroup
      {
         get
         {
            if (String.IsNullOrEmpty(_formValidationGroup))
               _formValidationGroup = String.Format("helferlein_Form_ValidationGroup_{0}", base.ModuleId);
            return _formValidationGroup;
         }
      }

      protected string UploadFolder
      {
         get
         {
            if (String.IsNullOrEmpty(_uploadFolder))
            {
               _uploadFolder = String.Format("{0}{1}helferlein\\helferlein_Form\\{2}\\{3}\\", base.PortalSettings.HomeDirectoryMapPath, (base.PortalSettings.HomeDirectoryMapPath.EndsWith("\\") ? String.Empty : "\\"), Base.UPLOAD_FOLDER, base.ModuleId);
               Helpers.CheckFolder(base.PortalId, String.Format("helferlein/helferlein_Form/{0}/{1}", Base.UPLOAD_FOLDER, base.ModuleId), true);
            }
            return _uploadFolder;
         }
      }


      protected string SharedResourceFile
      {
         get
         {
            return base.ControlPath + Localization.LocalResourceDirectory + "/" + Localization.LocalSharedResourceFile;
         }
      }
#endregion

#region Settings
      protected Double KeepDays
      {
         get
         {
            object o = Settings["KeepDays"];
            if (o == null)
               return 0;
            else
            {
               try { return Convert.ToDouble(o); }
               catch { return 0; }
            }
         }
      }

      protected SubmitButtonsAppearance SubmitButtonAppearance
      {
         get
         {
            object o = base.Settings["SubmitButtons"];
            if (o == null)
               return SubmitButtonsAppearance.CommandButton;
            else
            {
               try { return (SubmitButtonsAppearance)Enum.GetValues(typeof(SubmitButtonsAppearance)).GetValue(Convert.ToInt32(Convert.ToInt32(o) - 1)); }
               catch { return SubmitButtonsAppearance.Link; }
            }
         }
      }

      protected string FormHeaderTemplate
      {
         get
         {
            object o = base.Settings["FormHeaderTemplate"];
            if (o == null)
               return Base.DEFAULT_FORM_HEADER_TEMPLATE;
            else
            {
               try { return Server.HtmlDecode(Convert.ToString(o)); }
               catch { return Base.DEFAULT_FORM_HEADER_TEMPLATE; }
            }
         }
      }

      protected string FormItemTemplate
      {
         get
         {
            object o = base.Settings["FormItemTemplate"];
            if (o == null)
               return Base.DEFAULT_FORM_ITEM_TEMPLATE;
            else
            {
               try { return Server.HtmlDecode(Convert.ToString(o)); }
               catch { return Base.DEFAULT_FORM_ITEM_TEMPLATE; }
            }
         }
      }

      protected string LabelTemplate
      {
         get
         {
            object o = base.Settings["LabelTemplate"];
            if (o == null)
               return Base.DEFAULT_FORM_LABEL_TEMPLATE;
            else
            {
               try { return Server.HtmlDecode(Convert.ToString(o)); }
               catch { return Base.DEFAULT_FORM_LABEL_TEMPLATE; }
            }
         }
      }

      protected string FormFooterTemplate
      {
         get
         {
            object o = base.Settings["FormFooterTemplate"];
            if (o == null)
               return Base.DEFAULT_FORM_FOOTER_TEMPLATE;
            else
            {
               try { return Server.HtmlDecode(Convert.ToString(o)); }
               catch { return Base.DEFAULT_FORM_FOOTER_TEMPLATE; }
            }
         }
      }

      protected Unit Width
      {
         get
         {
            object o = base.Settings["Width"];
            if (o == null)
               return Unit.Parse("100%");
            else
            {
               try { return Unit.Parse(o.ToString()); }
               catch { return Unit.Parse("100%"); }
            }
         }
      }

      protected bool SubmitByEMail
      {
         get
         {
            object o = base.Settings["SubmitByEMail"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected bool SaveToDataBase
      {
         get
         {
            object o = base.Settings["SaveToDataBase"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected ShowAdditionalItems WhereToDisplayToDisplayApprovedSubmissions
      {
         get
         {
            object o = base.Settings["WhereToDisplayToDisplayApprovedSubmissions"];
            if (o == null)
               return ShowAdditionalItems.NotAtAll;
            else
            {
               try { return (ShowAdditionalItems)Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(Convert.ToInt32(Convert.ToInt32(o) - 1)); }
               catch { return ShowAdditionalItems.NotAtAll; }
            }
         }
      }

      protected bool Captcha
      {
         get
         {
            object o = base.Settings["Captcha"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected bool UnauthenticatedUsersOnly
      {
         get
         {
            object o = base.Settings["UnauthenticatedUsersOnly"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected RequiredFieldMarkerType RequiredFieldMarker
      {
         get
         {
            object o = base.Settings["RequiredFieldMarker"];
            if (o == null)
               return RequiredFieldMarkerType.StandardIcon;
            else
            {
               try { return (RequiredFieldMarkerType)Enum.GetValues(typeof(RequiredFieldMarkerType)).GetValue(Convert.ToInt32(o) - 1); }
               catch { return RequiredFieldMarkerType.StandardIcon; }
            }
         }
      }

      protected ShowAdditionalItems WhereToDisplayRequiredFieldMarkerExplanation
      {
         get
         {
            object o = base.Settings["WhereToDisplayRequiredFieldMarkerExplanation"];
            if (o == null)
               return ShowAdditionalItems.NotAtAll;
            else
            {
               try { return (ShowAdditionalItems)Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(Convert.ToInt32(Convert.ToInt32(o) - 1)); }
               catch { return ShowAdditionalItems.NotAtAll; }
            }
         }
      }

      protected bool AutoApprove
      {
         get
         {
            object o = base.Settings["AutoApprove"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected string Theme
      {
         get
         {
            string theme = Convert.ToString(base.Settings["Theme"]);
            if (String.IsNullOrEmpty(theme))
               theme = "Default [M]";
            else
            {
               // To avoid an error with the "old" theme format up to version 2.2.6
               if (!((theme.EndsWith(" [M]")) || (theme.EndsWith(" [P]"))))
                  theme = String.Format("{0} [M]", theme);
            }
            return theme;

         }
      }

      protected string RedirectURL
      {
         get
         {
            object o = base.Settings["RedirectURL"];
            if (o == null)
               return String.Empty;
            else
            {
               try { return Convert.ToString(o); }
               catch { return String.Empty; }
            }
         }
      }

      protected string RedirectURLType
      {
         get
         {
            object o = base.Settings["RedirectURLType"];
            if (o == null)
               return String.Empty;
            else
            {
               try { return Convert.ToString(o); }
               catch { return String.Empty; }
            }
         }
      }

      protected bool ValidationShowSummary
      {
         get
         {
            object o = base.Settings["ValidationShowSummary"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected bool ValidationShowMessageBox
      {
         get
         {
            object o = base.Settings["ValidationShowMessageBox"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected bool ShowDate
      {
         get
         {
            object o = base.Settings["ShowDate"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected bool ShowFlag
      {
         get
         {
            object o = base.Settings["ShowFlag"];
            if (o == null)
               return false;
            else
            {
               try { return Convert.ToBoolean(o); }
               catch { return false; }
            }
         }
      }

      protected string RenderAsHeadline
      {
         get
         {
            object o = base.Settings["RenderAsHeadline"];
            if (o == null)
               return String.Empty;
            else
            {
               try { return Convert.ToString(o); }
               catch { return String.Empty; }
            }
         }
      }

      protected bool UseHeadlineAsSubject
      {
         get { return (Convert.ToBoolean(base.Settings["UseHeadlineAsSubject"])); }
      }

      protected string HeadlineAlignment
      {
         get
         {
            object o = base.Settings["HeadlineAlignment"];
            if (o == null)
               return String.Empty;
            else
            {
               try { return Convert.ToString(o); }
               catch { return String.Empty; }
            }
         }
      }

      protected MailFormat EMailFormat
      {
         get
         {
            object o = base.Settings["EMailFormat"];
            if (o == null)
               return MailFormat.Text;
            else
            {
               try { return (MailFormat)Enum.GetValues(typeof(MailFormat)).GetValue(Convert.ToInt32(base.Settings["EMailFormat"])); }
               catch { return MailFormat.Text; }
            }
         }
      }

      protected string SenderAddress
      {
         get
         {
            object o = base.Settings["SenderAddress"];
            if (o == null)
               return String.Empty;
            else
            {
               try { return Convert.ToString(o); }
               catch { return String.Empty; }
            }
         }
      }

      protected string ReplyToAddress
      {
         get
         {
            object o = base.Settings["ReplyToAddress"];
            if (o == null)
               return this.SenderAddress;
            else
               return o.ToString();
         }
      }

      protected string EMailAddress
      {
         get
         {
            object o = base.Settings["EMailAddress"];
            if (o == null)
               return PortalSettings.Email;
            else
            {
               try { return Convert.ToString(o); }
               catch { return PortalSettings.Email; }
            }
         }
      }

      protected bool IncludeIPAddressInEmail
      {
         get { return Convert.ToBoolean(base.Settings["IncludeIPAddressInEmail"]); }
      }
#endregion

#region Event Handlers
      protected void Page_Init(object sender, EventArgs e)
      {
         // Set Title
         BabelFishInfo moduleTitle = this.BabelFishController.GetString(base.PortalId, CultureInfo.CurrentCulture.Name,
            String.Format("helferlein.Form.Settings.{0}", base.ModuleId), "ModuleTitle", true);
         if (moduleTitle != null)
            base.ModuleConfiguration.ModuleTitle = moduleTitle.DisplayValue;

         this.SubmitButtonAsCommandButton.Click += new EventHandler(this.SubmitButton_Click);
         this.BackButtonAsCommandButton.Click += new EventHandler(this.BackButton_Click);
      }

      protected void Page_Load(object sender, EventArgs e)
      {
         // Set Theme
         this.SetTheme();
         // Get List of FormControls
         this.TheForm = this.FormItemController.GetAll(base.ModuleId);
         // Set width for the form panel
         this.FormPanel.Width = this.Width;

         // The form only makes sense, if there are FormItems defined and at least one of the Submission Settings is selected
         if ((this.TheForm.Count > 0) && ((this.SubmitByEMail) || (this.SaveToDataBase)))
         {
            // Create Submit button
            switch (this.SubmitButtonAppearance)
            {
               case SubmitButtonsAppearance.Link:
                  this.SubmitButtonAsLink.Visible = true;
                  this.SubmitButtonAsButton.Visible = false;
                  this.SubmitButtonAsCommandButton.Visible = false;

                  this.SubmitButtonAsLink.TabIndex = (short)(this.MaxSortOrderValue + 2);
                  this.SubmitButtonAsLink.ValidationGroup = this.FormValidationGroup;
                  this.SubmitButtonAsLink.Text = Localization.GetString("SubmitButton.Text", LocalResourceFile);
                  break;
               case SubmitButtonsAppearance.Button:
                  this.SubmitButtonAsLink.Visible = false;
                  this.SubmitButtonAsButton.Visible = true;
                  this.SubmitButtonAsCommandButton.Visible = false;

                  this.SubmitButtonAsButton.TabIndex = (short)(this.MaxSortOrderValue + 2);
                  this.SubmitButtonAsButton.ValidationGroup = this.FormValidationGroup;
                  this.SubmitButtonAsButton.Text = Localization.GetString("SubmitButton.Text", LocalResourceFile);
                  break;
               default:
                  this.SubmitButtonAsLink.Visible = false;
                  this.SubmitButtonAsButton.Visible = false;
                  this.SubmitButtonAsCommandButton.Visible = true;

                  this.SubmitButtonAsCommandButton.TabIndex = (short)(this.MaxSortOrderValue + 2);
                  this.SubmitButtonAsCommandButton.ValidationGroup = this.FormValidationGroup;
                  break;
            }

            // Display submissions above the form
            if (((this.WhereToDisplayToDisplayApprovedSubmissions == ShowAdditionalItems.AboveTheForm) && (this.FormSubmissions.Count > 0)) || (this.WhereToDisplayRequiredFieldMarkerExplanation == ShowAdditionalItems.AboveTheForm))
            {
               this.AdditionalItemsAbove.Visible = true;
               if ((this.WhereToDisplayToDisplayApprovedSubmissions == ShowAdditionalItems.AboveTheForm) && (this.FormSubmissions.Count > 0))
                  this.AdditionalItemsAbove.Controls.Add(ApprovedSubmissionsLabel());
            }

            this.FormPlaceHolder.Controls.Add(new LiteralControl(this.FormHeaderTemplate));

            foreach (FormItemInfo formItem in this.TheForm)
            {
               if (formItem.FormItemType == FormItemType.Label)
                  CreateLabel(formItem);
               else
                  CreateItem(formItem);
            }

            this.FormPlaceHolder.Controls.Add(new LiteralControl(this.FormFooterTemplate));

            // Hide message
            this.Message.Visible = false;

            // Create Captcha
            if ((this.Captcha) && (((this.UnauthenticatedUsersOnly) && (base.UserId < 0)) || (!(this.UnauthenticatedUsersOnly))))
               CreateCaptcha();

            // Explain Reqired Symbol
            if (this.HasRequiredValidators)
            {
               if (this.WhereToDisplayRequiredFieldMarkerExplanation != ShowAdditionalItems.NotAtAll)
               {
                  Panel whereToDisplayRequiredFieldMarkerExplanationPanel = (this.WhereToDisplayRequiredFieldMarkerExplanation == ShowAdditionalItems.AboveTheForm ? this.AdditionalItemsAbove : this.AdditionalItemsBelow);
                  StringBuilder requiredFieldMarkerExplanation = new StringBuilder();
                  switch (this.RequiredFieldMarker)
                  {
                     case RequiredFieldMarkerType.Asterisk:
                        requiredFieldMarkerExplanation.Append("<div id=\"ExplainRequired\">*&nbsp;&nbsp;<span class=\"Normal\">");
                        requiredFieldMarkerExplanation.Append(Localization.GetString("Required.Text", base.LocalResourceFile));
                        requiredFieldMarkerExplanation.Append("</span>");
                        break;
                     case RequiredFieldMarkerType.StandardIcon:
                        requiredFieldMarkerExplanation.Append("<div id=\"ExplainRequired\"><img src=\"");
                        requiredFieldMarkerExplanation.Append(ResolveUrl("~/images/required.gif"));
                        requiredFieldMarkerExplanation.Append("\">&nbsp;&nbsp;<span class=\"Normal\">");
                        requiredFieldMarkerExplanation.Append(Localization.GetString("Required.Text", base.LocalResourceFile));
                        requiredFieldMarkerExplanation.Append("</span>");
                        break;
                     default:
                        break;
                  }
                  if (this.WhereToDisplayRequiredFieldMarkerExplanation == ShowAdditionalItems.AboveTheForm)
                     requiredFieldMarkerExplanation.Append("<hr /></div>");
                  else
                  {
                     requiredFieldMarkerExplanation.Insert(0, "<hr />");
                     requiredFieldMarkerExplanation.Append("</div>");
                  }
                  whereToDisplayRequiredFieldMarkerExplanationPanel.Controls.Add(new LiteralControl(requiredFieldMarkerExplanation.ToString()));
               }
            }

            // Display submissions below the form
            if (((this.WhereToDisplayToDisplayApprovedSubmissions == ShowAdditionalItems.BelowTheForm) && (this.FormSubmissions.Count > 0)) || (this.WhereToDisplayRequiredFieldMarkerExplanation == ShowAdditionalItems.BelowTheForm))
            {
               this.AdditionalItemsBelow.Visible = true;
               if ((this.WhereToDisplayToDisplayApprovedSubmissions == ShowAdditionalItems.BelowTheForm) && (this.FormSubmissions.Count > 0))
               {
                  this.AdditionalItemsBelow.Controls.Add(new LiteralControl("<hr />"));
                  this.AdditionalItemsBelow.Controls.Add(ApprovedSubmissionsLabel());
               }
            }
         }
         // No form item defined and/or submission mode not set
         else
         {
            // Hide Submit button
            this.SubmitButtonAsLink.Visible = false;
            this.SubmitButtonAsButton.Visible = false;
            this.SubmitButtonAsCommandButton.Visible = false;

            // Display message
            StringBuilder messageText = new StringBuilder();
            messageText.Append(Localization.GetString("FormNotSetupProperly.Text", base.LocalResourceFile));
            messageText.Append("<br /><br /><ul>");
            if (this.TheForm.Count == 0)
            {
               messageText.Append("<li>");
               messageText.Append(Localization.GetString("AddFormItems.Text", LocalResourceFile));
               messageText.Append("</li>");
            }
            if ((!(this.SubmitByEMail)) && (!(this.SaveToDataBase)))
            {
               messageText.Append("<li>");
               messageText.Append(Localization.GetString("SelectSubmissionOptions.Text", LocalResourceFile));
               messageText.Append("</li>");
            }
            messageText.Append("</ul>");

            this.Message.Text = messageText.ToString();
            this.Message.Visible = true;
            this.Message.CssClass = "NormalRed";
         }
      }

      protected void SubmitButton_Click(object sender, EventArgs e)
      {
         // First, check CAPTCHA
         if (((formCaptcha != null) && (formCaptcha.IsValid)) || (formCaptcha == null))
         {
            // Then validate page
            Page.Validate(this.FormValidationGroup);

            if (Page.IsValid)
            {
               StringBuilder messageText = new StringBuilder();

               // Then create the form submission XML string
               string submissionXML = CreateFormSubmissionXML();
               if (submissionXML.Substring(0, 7) == "[ERROR]")
               {
                  string[] error = submissionXML.Substring(7).Split(new char[] { ';' });
                  switch (error[0])
                  {
                     case "RestrictedFileType":
                        string allowedExtensions;
                        if (!(this.HostSettings.TryGetValue("FileExtensions", out allowedExtensions)))
                           allowedExtensions = String.Empty;
                        messageText.Append(String.Format(Localization.GetString("RestrictedFileType.Text"), error[1], allowedExtensions.ToLower().Replace(",", ", *.")));
                        break;
                     default:
                        messageText.Append(Localization.GetString("SubmitError.Text", base.LocalResourceFile));
                        messageText.Append("<br />- ");
                        messageText.Append(error[0]);
                        messageText.Append(" -");
                        break;
                  }
               }
               // submission is OK
               else
               {
                  // Assign values to new submission object
                  FormSubmissionInfo fsi = new FormSubmissionInfo();
                  fsi.ModuleID = base.ModuleId;
                  fsi.FormSubmissionApproved = this.AutoApprove;
                  fsi.FormSubmissionDate = DateTime.Now;
                  fsi.FormSubmission = submissionXML;
                  fsi.FormSubmissionIPAddress = Request.ServerVariables["REMOTE_ADDR"];
                  fsi.FormSubmissionLocale = CultureInfo.CurrentCulture.Name;

                  bool sendMailError = false;
                  bool databaseError = false;
                  // Send E-Mail
                  if (this.SubmitByEMail)
                     sendMailError = SendEmail(fsi);

                  // Save to Database
                  if (this.SaveToDataBase)
                     databaseError = (this.FormSubmissionController.Add(fsi) < 1);

                  // Error Message
                  if (sendMailError || databaseError)
                  {
                     if (sendMailError)
                     {
                        messageText.Append(Localization.GetString("SubmitMailError.Text", base.LocalResourceFile));
                        messageText.Append("<br />");
                     }
                     if (databaseError)
                     {
                        messageText.Append(Localization.GetString("SubmitDatabaseError.Text", base.LocalResourceFile));
                        messageText.Append("<br />");
                     }
                  }
                  else
                  {
                     if (!(String.IsNullOrEmpty(this.RedirectURL)))
                     {
                        if (this.RedirectURLType == "T")
                           Response.Redirect(Globals.NavigateURL(Convert.ToInt32(this.RedirectURL)), false);
                        else // redirect type is empty or "U"
                           Response.Redirect(this.RedirectURL, false);
                     }
                  }
               }

               if (messageText.Length == 0)
               {
                  messageText.Append(Localization.GetString("SubmitSuccess.Text", LocalResourceFile));
                  this.Message.CssClass = "Normal";
               }
               else
               {
                  this.Message.CssClass = "NormalRed";
               }

               messageText.Append("<hr />");
               this.Message.Text = messageText.ToString();
               this.Message.Visible = true;

               // Hide form, submissions and submit button
               this.FormPlaceHolder.Visible = false;
               this.AdditionalItemsAbove.Visible = false;
               this.AdditionalItemsBelow.Visible = false;
               this.SubmitButtonAsLink.Visible = false;
               this.SubmitButtonAsButton.Visible = false;
               this.SubmitButtonAsCommandButton.Visible = false;

               // Display Back button and error/success message
               this.BackButtonAsLink.Visible = false;
               this.BackButtonAsButton.Visible = false;
               this.BackButtonAsCommandButton.Visible = false;
               switch (this.SubmitButtonAppearance)
               {
                  case SubmitButtonsAppearance.Link:
                     this.BackButtonAsLink.Visible = true;
                     this.BackButtonAsLink.Text = Localization.GetString("cmdBack.Text");
                     break;
                  case SubmitButtonsAppearance.Button:
                     this.BackButtonAsButton.Visible = true;
                     this.BackButtonAsButton.Text = Localization.GetString("cmdBack.Text");
                     break;
                  default:
                     this.BackButtonAsCommandButton.Visible = true;
                     break;
               }
            }
         }
      }

      protected void BackButton_Click(object sender, EventArgs e)
      {
         // Reload the page. This creates the form from scratch
         // and avoids the sent field values to be displayed again.
         // Also the Captcha (if there) will not display the error message.
         Response.Redirect(Globals.NavigateURL(), false);
      }

      protected void RemoveLineBreakFromLabelControl(object sender, EventArgs e)
      {
         LabelControl label = (LabelControl)sender;
         label.Controls[1].Visible = false;
      }
#endregion

#region Form Methods
      protected void FormValidationSummary_Load(object sender, EventArgs e)
      {
         ValidationSummary formValidationSummary = (ValidationSummary)sender;
         formValidationSummary.ValidationGroup = this.FormValidationGroup;
         formValidationSummary.ShowSummary = this.ValidationShowSummary;
         formValidationSummary.ShowMessageBox = this.ValidationShowMessageBox;
      }

      private void CreateCaptcha()
      {
         formCaptcha = new CaptchaControl();
         formCaptcha.Text = Localization.GetString("FormCaptcha.Text", LocalResourceFile);
         formCaptcha.CssClass = "Normal CaptchaStyle";
         formCaptcha.CaptchaHeight = Unit.Parse("60px");
         formCaptcha.CaptchaWidth = Unit.Parse("180px");
         formCaptcha.CaptchaLength = 8;
         formCaptcha.ErrorMessage = Localization.GetString("FormCaptcha.ErrorMessage", LocalResourceFile);
         formCaptcha.CaptchaChars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
         formCaptcha.ErrorStyle.CssClass = "NormalRed";
         formCaptcha.TabIndex = (short)(this.MaxSortOrderValue + 1);
         this.FormPlaceHolder.Controls.Add(formCaptcha);
      }

      private void CreateLabel(FormItemInfo formItem)
      {
         string labelTemplate = (String.IsNullOrEmpty(formItem.FormItemTemplate) ? this.LabelTemplate : Server.HtmlDecode(formItem.FormItemTemplate));
         int position = 0;

         bool pencilCreated = false;
         PlaceHolder pencilPlaceHolder = new PlaceHolder();
         this.FormPlaceHolder.Controls.Add(pencilPlaceHolder);

         do
         {
            if (position >= labelTemplate.Length)
               break;

            if (labelTemplate.Substring(position, 1) == "[")
            {
               if (labelTemplate.Substring(position, 8) == "[PENCIL]")
               {
                  pencilCreated = true;
                  if (base.IsEditable)
                     CreatePencil(formItem);
                  else
                     this.FormPlaceHolder.Controls.Add(new LiteralControl("&nbsp;"));
                  position += 8;
               }
               else if (labelTemplate.Substring(position, 10) == "[FORMITEM]")
               {
                  Label formItemLabel = new Label();
                  formItemLabel.Text = Server.HtmlDecode(this.TokenReplace.ReplaceEnvironmentTokens(formItem.FormItemValue));
                  formItemLabel.ID = String.Format("ctl_{0}", formItem.FormItemID);
                  formItemLabel.CssClass = "SubHead LabelItemStyle";
                  this.FormPlaceHolder.Controls.Add(formItemLabel);
                  position += 10;
               }
               else
               {
                  this.FormPlaceHolder.Controls.Add(new LiteralControl(labelTemplate.Substring(position, 1)));
                  position++;
               }
            }
            else
            {
               this.FormPlaceHolder.Controls.Add(new LiteralControl(labelTemplate.Substring(position, 1)));
               position++;
            }
         }
         while (true);

         if (!(pencilCreated) && (base.IsEditable))
         {
            // Just in case someone forgot to add a pencil in the template...
            this.CreatePencil(formItem, pencilPlaceHolder);
         }
      }

      private void CreateItem(FormItemInfo formItem)
      {
         if ((formItem.FormItemType != FormItemType.SendCopy) || ((formItem.FormItemType == FormItemType.SendCopy) && (!(this.HideSendCopy)) && (!(base.IsEditable))) || ((formItem.FormItemType == FormItemType.SendCopy) && (base.IsEditable)))
         {
            string template = (String.IsNullOrEmpty(formItem.FormItemTemplate) ? this.FormItemTemplate : Server.HtmlDecode(formItem.FormItemTemplate));
            int position = 0;

            bool pencilCreated = false;
            PlaceHolder pencilPlaceHolder = new PlaceHolder();
            this.FormPlaceHolder.Controls.Add(pencilPlaceHolder);

            do
            {
               if (position >= template.Length)
                  break;

               if (template.Substring(position, 1) == "[")
               {
                  if ((template.Substring(position).Length >= 8) && (template.Substring(position, 8) == "[PENCIL]"))
                  {
                     pencilCreated = true;
                     if (base.IsEditable)
                        this.CreatePencil(formItem);
                     position += 8;
                  }
                  else if ((template.Substring(position).Length >= 7) && (template.Substring(position, 7) == "[LABEL]"))
                  {
                     if (((formItem.FormItemType != FormItemType.Checkbox) && (formItem.FormItemType != FormItemType.SendCopy) && (((formItem.FormItemType == FormItemType.Hidden) && (base.IsEditable)) || (formItem.FormItemType != FormItemType.Hidden))))
                        this.CreateFormItemLabel(formItem);
                     position += 7;
                  }
                  else if ((template.Substring(position).Length >= 22) && (template.Substring(position, 22) == "[LABEL[REQUIREDIMAGE]]"))
                  {
                     if (((formItem.FormItemType != FormItemType.Checkbox) && (formItem.FormItemType != FormItemType.SendCopy) && (((formItem.FormItemType == FormItemType.Hidden) && (base.IsEditable)) || (formItem.FormItemType != FormItemType.Hidden))))
                        this.CreateFormItemLabel(formItem, true);
                     position += 22;
                  }
                  else if ((template.Substring(position).Length) >= 10 && (template.Substring(position, 10) == "[FORMITEM]"))
                  {
                     this.CreateFormItem(formItem);
                     position += 10;
                     if (formItem.FormItemOther && !template.Contains("[OTHER]")) this.CreateFormItemOther(formItem);
                  }
                  else if ((template.Substring(position).Length) >= 7 && (template.Substring(position, 7) == "[OTHER]") && formItem.FormItemOther)
                  {
                     this.CreateFormItemOther(formItem);
                     position += 7;
                  }
                  // Code provided by user Lode_Leroy on CodePlex -->
                  else if ((template.Substring(position).Length >= 11) && (template.Substring(position, 11) == "[VALIDATOR]"))
                  {
                     if ((formItem.FormItemRequired) || (!(String.IsNullOrEmpty(formItem.ValidationExpression))))
                        this.CreateValidator(formItem);
                     position += 11;
                  }
                  else if ((template.Substring(position).Length >= 15) && (template.Substring(position, 15) == "[REQUIREDIMAGE]"))
                  {
                     if ((formItem.FormItemType != FormItemType.DropDownList) && (formItem.FormItemType != FormItemType.Hidden))
                        this.FormPlaceHolder.Controls.Add(this.GetRequiredImage(formItem));
                     position += 15;
                  }
                  else if ((template.Substring(position).Length >= 10) && (template.Substring(position, 10) == "[HELPICON]"))
                  {
                     if ((formItem.FormItemType != FormItemType.Checkbox) && (formItem.FormItemType != FormItemType.SendCopy) && (formItem.FormItemType != FormItemType.Hidden))
                        this.CreateFormItemLabel(formItem, false, false);
                     position += 10;
                  }
                  else
                  {
                     this.FormPlaceHolder.Controls.Add(new LiteralControl(template.Substring(position, 1)));
                     position++;
                  }
               }
               else
               {
                  this.FormPlaceHolder.Controls.Add(new LiteralControl(template.Substring(position, 1)));
                  position++;
               }
            }
            while (true);

            if (!(pencilCreated) && (base.IsEditable))
            {
               // Just in case someone forgot to add a pencil in the template...
               this.CreatePencil(formItem, pencilPlaceHolder);
            }
         }
      }

      private void CreatePencil(FormItemInfo formItem)
      {
         this.CreatePencil(formItem, this.FormPlaceHolder);
      }

      private void CreatePencil(FormItemInfo formItem, PlaceHolder whereToAddIt)
      {
         HyperLink pencil = new HyperLink();
         pencil.NavigateUrl = EditUrl("FormItemID", formItem.FormItemID.ToString());
         pencil.ImageUrl = "~/images/edit.gif";
         pencil.ToolTip = Localization.GetString("cmdEdit.Text");
         pencil.BorderStyle = BorderStyle.None;
         whereToAddIt.Controls.Add(pencil);
         if ((formItem.FormItemType == FormItemType.SendCopy) && (this.HideSendCopy))
            this.FormPlaceHolder.Controls.Add(new LiteralControl(String.Format("<span class=\"NormalRed\">{0}</span>", Localization.GetString("SendCopyDisabled.Text", base.LocalResourceFile))));
      }

      private void CreateFormItemLabel(FormItemInfo formItem)
      {
         this.CreateFormItemLabel(formItem, false, true);
      }

      private void CreateFormItemLabel(FormItemInfo formItem, bool includeRequiredImage)
      {
         this.CreateFormItemLabel(formItem, includeRequiredImage, true);
      }

      private void CreateFormItemLabel(FormItemInfo formItem, bool includeRequiredImage, bool displayLabelText)
      {
         StringBuilder labelText = new StringBuilder();
         if (!(String.IsNullOrEmpty(formItem.FormItemHelpText)))
         {
            LabelControl label = (LabelControl)LoadControl("~/controls/labelcontrol.ascx");
            if (DotNetNuke.Common.Globals.DataBaseVersion.Major < 6)
            {
               Image helpImage = (Image)label.FindControl("imgHelp");
               helpImage.CssClass = "HelpImageStyle";
            }
            else
            {
               LinkButton helpImage = (LinkButton)label.FindControl("cmdHelp");
               helpImage.CssClass = "HelpImageStyle";
            }
            if (displayLabelText)
            {
               labelText.Append(formItem.FormItemLabel);
               if (includeRequiredImage)
                  labelText.Append(this.GetRequiredImage(formItem).Text);
               labelText.Append(":");
            }
            else
            {
               label.PreRender += new EventHandler(RemoveLineBreakFromLabelControl);
               if (includeRequiredImage)
                  labelText.Append(this.GetRequiredImage(formItem).Text);
            }
            label.Text = labelText.ToString();
            label.HelpText = formItem.FormItemHelpText;
            label.CssClass = "SubHead";
            this.FormPlaceHolder.Controls.Add(label);
         }
         else
         {
            Label label = new Label();
            if (displayLabelText)
            {
               labelText.Append(formItem.FormItemLabel);
               if (includeRequiredImage)
                  labelText.Append(this.GetRequiredImage(formItem).Text);
               // Code provided by user Lode_Leroy on CodePlex
               if (!(formItem.FormItemOther && (formItem.FormItemRepeatColumns != null) && (formItem.FormItemRepeatColumns.Value > 0)))
                  labelText.Append(":");
               // This <br /> is because of the LabelControl ends with an <br /> tag... just
               // to make it behave in the same way...
               labelText.Append("<br />");
            }
            else
            {
               if (includeRequiredImage)
                  labelText.Append(this.GetRequiredImage(formItem).Text);
            }
            label.CssClass = "SubHead";
            label.Text = labelText.ToString();
            this.FormPlaceHolder.Controls.Add(label);
         }
      }

      protected void CreateFormItem(FormItemInfo formItem)
      {
         BabelFishInfo aquarium;
         string formItemID = String.Format("ctl_{0}", formItem.FormItemID);

         try
         {
            switch (formItem.FormItemType)
            {
               case FormItemType.TextBox:
                  TextBox formItemTextBox = new TextBox();
                  if (!(String.IsNullOrEmpty(formItem.FormItemValue)))
                  {
                     switch (formItem.FormItemValue)
                     {
                        case "[FULLNAME]":
                           formItemTextBox.Text = String.Format("{0} {1}", UserInfo.FirstName, UserInfo.LastName);
                           break;
                        case "[FIRSTNAME]":
                           formItemTextBox.Text = UserInfo.FirstName;
                           break;
                        case "[LASTNAME]":
                           formItemTextBox.Text = UserInfo.LastName;
                           break;
                        case "[DISPLAYNAME]":
                           formItemTextBox.Text = UserInfo.DisplayName;
                           break;
                        case "[USERNAME]":
                           formItemTextBox.Text = UserInfo.Username;
                           break;
                        default:
                           formItemTextBox.Text = this.TokenReplace.ReplaceEnvironmentTokens(formItem.FormItemValue);
                           break;
                     }
                  }
                  formItemTextBox.ID = formItemID;
                  formItemTextBox.TextMode = TextBoxMode.SingleLine;
                  formItemTextBox.CssClass = "NormalTextBox";
                  if ((formItem.Width != null) && (formItem.Width.Value > 0))
                     formItemTextBox.Width = Unit.Parse(formItem.Width.ToString());
                  formItemTextBox.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemTextBox);
                  break;
               case FormItemType.TextArea:
                  TextBox formItemTextArea = new TextBox();
                  formItemTextArea.Text = this.TokenReplace.ReplaceEnvironmentTokens(formItem.FormItemValue);
                  formItemTextArea.ID = formItemID;
                  // Textarea is multi-line
                  formItemTextArea.TextMode = TextBoxMode.MultiLine;
                  formItemTextArea.CssClass = "NormalTextBox";
                  if ((formItem.Height != null) && (formItem.Height > 0))
                     // formItemTextArea.Rows = formItem.Height.Value;
                     formItemTextArea.Height = Unit.Parse(String.Format("{0}em", formItem.Height.Value + 1));
                  else
                     // Default to 6 rows...
                     formItemTextArea.Height = Unit.Parse("7em");
                  if ((formItem.Width != null) && (formItem.Width.Value > 0))
                  {
                     formItemTextArea.Width = Unit.Parse(formItem.Width.ToString());
                  }
                  formItemTextArea.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemTextArea);
                  break;
               case FormItemType.DropDownList:
                  DropDownList formItemDropDownList = new DropDownList();
                  aquarium = this.BabelFishController.GetString(base.PortalId, CultureInfo.CurrentCulture.Name, String.Format("helferlein.Form.FormItem.{0}", formItem.FormItemID), "FormItemValue");
                  formItemDropDownList.DataSource = this.LocalizedDataSource(aquarium, formItem.FormItemID, formItem.FormItemOther);
                  formItemDropDownList.DataValueField = "key";
                  formItemDropDownList.DataTextField = "value";
                  formItemDropDownList.DataBind();
                  formItemDropDownList.ID = formItemID;
                  formItemDropDownList.CssClass = "NormalTextBox";
                  if (!(String.IsNullOrEmpty(formItem.FormItemSelectedValue)))
                  {
                     if (formItemDropDownList.Items.FindByText(formItem.FormItemSelectedValue) != null)
                        formItemDropDownList.SelectedValue = formItemDropDownList.Items.FindByText(formItem.FormItemSelectedValue).Value;
                     else
                     {
                        try
                        {
                           if (formItem.FormItemSelectedValue == "[OTHER]")
                              formItemDropDownList.SelectedValue = String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID);
                           else
                              formItemDropDownList.SelectedValue = formItem.FormItemSelectedValue;
                        }
                        catch { }
                     }
                  }
                  formItemDropDownList.TabIndex = (short)formItem.SortValue.Value;
                  if (formItem.FormItemOther)
                  {
                     formItemDropDownList.AutoPostBack = true;
                     formItemDropDownList.SelectedIndexChanged += new EventHandler(this.FormItemDropDownList_SelectedIndexChanged);
                  }
                  this.FormPlaceHolder.Controls.Add(formItemDropDownList);
                  break;
               case FormItemType.MultipleSelect:
                  CheckBoxList formItemCheckBoxList = new CheckBoxList();
                  aquarium = this.BabelFishController.GetString(base.PortalId, CultureInfo.CurrentCulture.Name, String.Format("helferlein.Form.FormItem.{0}", formItem.FormItemID), "FormItemValue");
                  formItemCheckBoxList.DataSource = this.LocalizedDataSource(aquarium, formItem.FormItemID, formItem.FormItemOther);
                  formItemCheckBoxList.DataValueField = "key";
                  formItemCheckBoxList.DataTextField = "value";
                  formItemCheckBoxList.DataBind();
                  formItemCheckBoxList.ID = formItemID;
                  formItemCheckBoxList.CssClass = "Normal";
                  if ((formItem.FormItemRepeatColumns != null) && (formItem.FormItemRepeatColumns.Value > 0))
                     formItemCheckBoxList.RepeatColumns = Convert.ToInt32(formItem.FormItemRepeatColumns);
                  else
                     formItemCheckBoxList.RepeatColumns = 1;
                  formItemCheckBoxList.RepeatDirection = RepeatDirection.Vertical;
                  formItemCheckBoxList.RepeatLayout = RepeatLayout.Table;

                  string[] selectedItems = formItem.FormItemSelectedValue.Split(new string[] { "\n", ";" }, StringSplitOptions.RemoveEmptyEntries);
                  foreach (string s in selectedItems)
                  {
                     if (formItemCheckBoxList.Items.FindByText(s) != null)
                        formItemCheckBoxList.Items.FindByText(s).Selected = true;
                     else
                     {
                        try
                        {
                           if (s == "[OTHER]")
                              formItemCheckBoxList.Items.FindByValue(String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID)).Selected = true;
                           else
                              formItemCheckBoxList.Items.FindByValue(s).Selected = true;
                        }
                        catch { }
                     }
                  }
                  formItemCheckBoxList.TextAlign = TextAlign.Right;
                  formItemCheckBoxList.TabIndex = (short)formItem.SortValue.Value;
                  if (formItem.FormItemOther)
                  {
                     formItemCheckBoxList.AutoPostBack = true;
                     formItemCheckBoxList.SelectedIndexChanged += new EventHandler(this.FormItemCheckBoxList_SelectedIndexChanged);
                  }
                  this.FormPlaceHolder.Controls.Add(formItemCheckBoxList);
                  break;
               case FormItemType.Checkbox:
                  CheckBox formItemCheckBox = new CheckBox();
                  try
                  {
                     formItemCheckBox.Checked = Convert.ToBoolean(formItem.FormItemValue);
                  }
                  catch
                  {
                     formItemCheckBox.Checked = false;
                  }
                  formItemCheckBox.Text = formItem.FormItemLabel;
                  formItemCheckBox.CssClass = "Normal";
                  formItemCheckBox.ID = formItemID;
                  formItemCheckBox.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemCheckBox);
                  break;
               case FormItemType.RadioButtonList:
                  RadioButtonList formItemRadioButtonList = new RadioButtonList();
                  aquarium = this.BabelFishController.GetString(base.PortalId, CultureInfo.CurrentCulture.Name, String.Format("helferlein.Form.FormItem.{0}", formItem.FormItemID), "FormItemValue");
                  formItemRadioButtonList.DataSource = this.LocalizedDataSource(aquarium, formItem.FormItemID, formItem.FormItemOther);
                  formItemRadioButtonList.DataValueField = "key";
                  formItemRadioButtonList.DataTextField = "value";
                  formItemRadioButtonList.DataBind();
                  formItemRadioButtonList.ID = formItemID;
                  formItemRadioButtonList.CssClass = "Normal";
                  if ((formItem.FormItemRepeatColumns != null) && (formItem.FormItemRepeatColumns.Value > 0))
                     formItemRadioButtonList.RepeatColumns = Convert.ToInt32(formItem.FormItemRepeatColumns);
                  else
                     formItemRadioButtonList.RepeatColumns = 1;
                  if (!(String.IsNullOrEmpty(formItem.FormItemSelectedValue)))
                  {
                     if (formItemRadioButtonList.Items.FindByText(formItem.FormItemSelectedValue) != null)
                        formItemRadioButtonList.SelectedValue = formItemRadioButtonList.Items.FindByText(formItem.FormItemSelectedValue).Value;
                     else
                     {
                        try
                        {
                           if (formItem.FormItemSelectedValue == "[OTHER]")
                              formItemRadioButtonList.SelectedValue = String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID);
                           else
                              formItemRadioButtonList.SelectedValue = formItem.FormItemSelectedValue;
                        }
                        catch { }
                     }
                  }
                  formItemRadioButtonList.TabIndex = (short)formItem.SortValue.Value;
                  if (formItem.FormItemOther)
                  {
                     formItemRadioButtonList.AutoPostBack = true;
                     formItemRadioButtonList.SelectedIndexChanged += new EventHandler(this.FormItemRadioButtonList_SelectedIndexChanged);
                  }
                  this.FormPlaceHolder.Controls.Add(formItemRadioButtonList);
                  break;
               case FormItemType.EMailAddress:
                  TextBox formItemEmailAddressTextBox = new TextBox();
                  formItemEmailAddressTextBox.CssClass = "NormalTextBox";
                  if (!(string.IsNullOrEmpty(formItem.FormItemValue)))
                  {
                     switch (formItem.FormItemValue)
                     {
                        case "[EMAIL]":
                           formItemEmailAddressTextBox.Text = UserInfo.Email;
                           break;
                        default:
                           formItemEmailAddressTextBox.Text = this.TokenReplace.ReplaceEnvironmentTokens(formItem.FormItemValue);
                           break;
                     }
                  }
                  formItemEmailAddressTextBox.ID = formItemID;
                  formItemEmailAddressTextBox.TextMode = TextBoxMode.SingleLine;
                  if ((formItem.Width != null) && (formItem.Width.Value > 0))
                  {
                     formItemEmailAddressTextBox.Width = Unit.Parse(formItem.Width.ToString());
                  }
                  formItemEmailAddressTextBox.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemEmailAddressTextBox);
                  break;
               case FormItemType.WebSite:
                  DropDownList formItemWebSiteDropDownList = new DropDownList();
                  formItemWebSiteDropDownList.ID = String.Format("{0}_DropDownList", formItemID);
                  ListItem li = new ListItem();
                  li.Value = "http://";
                  li.Text = "http://";
                  formItemWebSiteDropDownList.Items.Add(li);
                  li = new ListItem();
                  li.Value = "https://";
                  li.Text = "https://";
                  formItemWebSiteDropDownList.Items.Add(li);
                  TextBox formItemWebSiteTextBox = new TextBox();
                  formItemWebSiteTextBox.ID = String.Format("{0}_TextBox", formItemID);
                  formItemWebSiteTextBox.TextMode = TextBoxMode.SingleLine;
                  if ((formItem.Width != null) && (formItem.Width.Value > 0))
                  {
                     formItemWebSiteTextBox.Width = Unit.Parse(formItem.Width.ToString());
                  }
                  formItemWebSiteDropDownList.TabIndex = (short)formItem.SortValue.Value;
                  formItemWebSiteTextBox.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemWebSiteDropDownList);
                  this.FormPlaceHolder.Controls.Add(formItemWebSiteTextBox);
                  break;
               case FormItemType.Date:
                  TextBox formItemDateTextBox = new TextBox();
                  formItemDateTextBox.ID = String.Format("{0}_DateTextBox", formItemID);
                  formItemDateTextBox.TextMode = TextBoxMode.SingleLine;
                  formItemDateTextBox.CssClass = "NormalTextBox";
                  if (!(string.IsNullOrEmpty(formItem.FormItemValue)))
                  {
                     formItemDateTextBox.Text = DateTime.FromBinary(Convert.ToInt64(formItem.FormItemValue)).ToString("d");
                  }
                  if ((formItem.Width != null) && (formItem.Width.Value > 0))
                  {
                     formItemDateTextBox.Width = Unit.Parse(formItem.Width.ToString());
                  }
                  formItemDateTextBox.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemDateTextBox);
                  this.FormPlaceHolder.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                  HyperLink formItemDateLink = new HyperLink();
                  formItemDateLink.ID = String.Format("{0}_DateLink", formItemID);
                  formItemDateLink.CssClass = "CommandButton";
                  formItemDateLink.Text = String.Format("<img src=\"{0}/images/calendar.png\" border=\"0\" />&nbsp;&nbsp;{1}", DotNetNuke.Common.Globals.ApplicationPath, Localization.GetString("Calendar"));
                  formItemDateLink.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(formItemDateTextBox);
                  formItemDateLink.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemDateLink);
                  break;
               case FormItemType.SendTo:
                  DropDownList formItemSendToDropDownList = new DropDownList();
                  formItemSendToDropDownList.ID = formItemID;
                  string[] recipients = formItem.FormItemValue.Split(new string[] { "\n", ";" }, StringSplitOptions.RemoveEmptyEntries);
                  foreach (string s in recipients)
                  {
                     string name = (s.Substring(0, s.IndexOf('[') - 1)).Trim();
                     string email = (s.Substring(s.IndexOf('[') + 1, s.IndexOf(']') - s.IndexOf('[') - 1)).Trim();
                     formItemSendToDropDownList.Items.Add(new ListItem(name, email));
                  }
                  if (!(String.IsNullOrEmpty(formItem.FormItemSelectedValue)))
                     formItemSendToDropDownList.SelectedValue = formItem.FormItemSelectedValue;
                  formItemSendToDropDownList.CssClass = "NormalTextBox";
                  formItemSendToDropDownList.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemSendToDropDownList);
                  break;
               case FormItemType.FileUpload:
                  FileUpload formItemFileUpload = new FileUpload();
                  formItemFileUpload.ID = formItemID;
                  formItemFileUpload.CssClass = "NormalTextBox";
                  formItemFileUpload.TabIndex = (short)formItem.SortValue.Value;
                  this.FormPlaceHolder.Controls.Add(formItemFileUpload);
                  break;
               case FormItemType.SendCopy:
                  if (!(this.HideSendCopy))
                  {
                     CheckBox formItemSendCopy = new CheckBox();
                     try
                     {
                        formItemSendCopy.Checked = Convert.ToBoolean(formItem.FormItemValue);
                     }
                     catch
                     {
                        formItemSendCopy.Checked = false;
                     }

                     if (!(String.IsNullOrEmpty(formItem.FormItemHelpText)))
                     {
                        formItemSendCopy.Text = "";
                        formItemSendCopy.ID = formItemID;
                        formItemSendCopy.TabIndex = (short)formItem.SortValue.Value;
                        this.FormPlaceHolder.Controls.Add(formItemSendCopy);
                        LabelControl label = (LabelControl)LoadControl("~/controls/labelcontrol.ascx");
                        if (DotNetNuke.Common.Globals.DataBaseVersion.Major < 6)
                        {
                           Image helpImage = (Image)label.FindControl("imgHelp");
                           helpImage.CssClass = "HelpImageStyle";
                        }
                        else
                        {
                           LinkButton helpImage = (LinkButton)label.FindControl("cmdHelp");
                           helpImage.CssClass = "HelpImageStyle";
                        }
                        label.Text = formItem.FormItemLabel;
                        label.HelpText = formItem.FormItemHelpText;
                        label.CssClass = "SubHead";
                        if (DotNetNuke.Common.Globals.DataBaseVersion.Major < 6)
                        {
                           this.FormPlaceHolder.Controls.Add(label);
                        }
                        else
                        {
                           Panel labelPanel = new Panel();
                           labelPanel.CssClass = "helferleinForm_FloatLeft";
                           labelPanel.Controls.Add(label);
                           this.FormPlaceHolder.Controls.Add(labelPanel);
                           this.FormPlaceHolder.Controls.Add(new LiteralControl("<div class=\"helferleinForm_ClearFloat\"></div>"));
                        }
                     }
                     else
                     {
                        formItemSendCopy.Text = formItem.FormItemLabel;
                        formItemSendCopy.CssClass = "SubHead";
                        formItemSendCopy.ID = formItemID;
                        formItemSendCopy.TabIndex = (short)formItem.SortValue.Value;
                        this.FormPlaceHolder.Controls.Add(formItemSendCopy);
                     }
                  }
                  break;
               case FormItemType.Hidden:
                  Label formItemHidden = new Label();
                  if (!(String.IsNullOrEmpty(formItem.FormItemValue)))
                  {
                     switch (formItem.FormItemValue)
                     {
                        case "[FULLNAME]":
                           formItemHidden.Text = String.Format("{0} {1}", UserInfo.FirstName, UserInfo.LastName);
                           break;
                        case "[FIRSTNAME]":
                           formItemHidden.Text = UserInfo.FirstName;
                           break;
                        case "[LASTNAME]":
                           formItemHidden.Text = UserInfo.LastName;
                           break;
                        case "[DISPLAYNAME]":
                           formItemHidden.Text = UserInfo.DisplayName;
                           break;
                        case "[USERNAME]":
                           formItemHidden.Text = UserInfo.Username;
                           break;
                        default:
                           formItemHidden.Text = this.TokenReplace.ReplaceEnvironmentTokens(formItem.FormItemValue);
                           break;
                     }
                     formItemHidden.ID = formItemID;
                     formItemHidden.CssClass = "Normal Disabled";
                     if (!(base.IsEditable))
                        formItemHidden.Visible = false;
                     this.FormPlaceHolder.Controls.Add(formItemHidden);
                     break;
                  }
                  break;
               default:
                  break;
            }
         }
         catch (Exception ex)
         {
            Label exceptionLabel = new Label();
            exceptionLabel.Text = String.Format(Localization.GetString("ItemCreationException.Text", base.LocalResourceFile), (String.IsNullOrEmpty(formItem.FormItemLabel) ? "?" : formItem.FormItemLabel), Localization.GetString("FormItemType." + Enum.GetNames(typeof(FormItemType))[Convert.ToInt32(formItem.FormItemType) - 1], this.SharedResourceFile), ex.Message);
            this.FormPlaceHolder.Controls.Add(exceptionLabel);
            formItem.FormItemRequired = false;
            formItem.ValidationExpression = String.Empty;
            Exceptions.LogException(ex);
         }
      }

      private void CreateValidator(FormItemInfo formItem)
      {
         RequiredFieldValidator formItemRequiredFieldValidator = new RequiredFieldValidator();
         DateValidator formItemDateValidator = new DateValidator();
         CheckBoxListValidator formItemCheckBoxListValidator = new CheckBoxListValidator();
         CheckBoxValidator formItemCheckBoxValidator = new CheckBoxValidator();
         RegExpValidator formItemRegExpValidator = new RegExpValidator();

         string validatorID = String.Format("val_{0}", formItem.FormItemID);
         string controlToValidate = String.Format("ctl_{0}", formItem.FormItemID);

         StringBuilder validationExpression = new StringBuilder();
         if (!(String.IsNullOrEmpty(formItem.ValidationExpression)))
         {
            if (!(formItem.ValidationExpression.StartsWith("^")))
               validationExpression.Append("^");
            validationExpression.Append(formItem.ValidationExpression);
            if ((!(formItem.ValidationExpression.EndsWith("$"))) || (formItem.ValidationExpression.EndsWith("\\$")))
               validationExpression.Append("$");
         }

         this.HasRequiredValidators = true;

         switch (formItem.FormItemType)
         {
            case FormItemType.TextBox:
               if (String.IsNullOrEmpty(formItem.ValidationExpression))
               {
                  formItemRequiredFieldValidator.ID = validatorID;
                  formItemRequiredFieldValidator.ValidationGroup = this.FormValidationGroup;
                  formItemRequiredFieldValidator.ControlToValidate = controlToValidate;
                  formItemRequiredFieldValidator.CssClass = "NormalRed";
                  formItemRequiredFieldValidator.ErrorMessage = String.Format(Localization.GetString("IsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
                  formItemRequiredFieldValidator.Text = "*";
                  this.FormPlaceHolder.Controls.Add(formItemRequiredFieldValidator);
                  this.HasRequiredValidators = true;
               }
               else
               {
                  formItemRegExpValidator.ID = validatorID;
                  formItemRegExpValidator.ValidationGroup = this.FormValidationGroup;
                  formItemRegExpValidator.ControlToValidate = controlToValidate;
                  formItemRegExpValidator.CssClass = "NormalRed";
                  formItemRegExpValidator.Required = formItem.FormItemRequired;
                  formItemRegExpValidator.RequiredErrorMessage = String.Format(Localization.GetString("IsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
                  formItemRegExpValidator.InvalidErrorMessage = String.Format(Localization.GetString("IsInvalid.Text", LocalResourceFile), formItem.FormItemLabel);
                  formItemRegExpValidator.ValidationExpression = validationExpression.ToString();
                  formItemRegExpValidator.Text = "*";
                  this.FormPlaceHolder.Controls.Add(formItemRegExpValidator);
                  this.HasRequiredValidators = formItem.FormItemRequired;
               }
               break;
            case FormItemType.TextArea:
               formItemRequiredFieldValidator.ID = validatorID;
               formItemRequiredFieldValidator.ValidationGroup = this.FormValidationGroup;
               formItemRequiredFieldValidator.ControlToValidate = controlToValidate;
               formItemRequiredFieldValidator.CssClass = "NormalRed";
               formItemRequiredFieldValidator.ErrorMessage = String.Format(Localization.GetString("IsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRequiredFieldValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemRequiredFieldValidator);
               this.HasRequiredValidators = true;
               break;
            case FormItemType.MultipleSelect:
               formItemCheckBoxListValidator.ID = validatorID;
               formItemCheckBoxListValidator.ValidationGroup = this.FormValidationGroup;
               formItemCheckBoxListValidator.ControlToValidate = controlToValidate;
               formItemCheckBoxListValidator.CssClass = "NormalRed";
               formItemCheckBoxListValidator.MinimumNumberOfSelectedCheckBoxes = 1;
               formItemCheckBoxListValidator.ErrorMessage = String.Format(Localization.GetString("MinimumOneMustBeChecked.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemCheckBoxListValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemCheckBoxListValidator);
               this.HasRequiredValidators = true;
               break;
            case FormItemType.Checkbox:
               formItemCheckBoxValidator.ID = validatorID;
               formItemCheckBoxValidator.ValidationGroup = this.FormValidationGroup;
               formItemCheckBoxValidator.ControlToValidate = controlToValidate;
               formItemCheckBoxValidator.CssClass = "NormalRed";
               formItemCheckBoxValidator.MustBeChecked = true;
               formItemCheckBoxValidator.ErrorMessage = String.Format(Localization.GetString("MustBeChecked.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemCheckBoxValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemCheckBoxValidator);
               this.HasRequiredValidators = true;
               break;
            case FormItemType.RadioButtonList:
               formItemRequiredFieldValidator.ID = validatorID;
               formItemRequiredFieldValidator.ValidationGroup = this.FormValidationGroup;
               formItemRequiredFieldValidator.ControlToValidate = controlToValidate;
               formItemRequiredFieldValidator.CssClass = "NormalRed";
               formItemRequiredFieldValidator.ErrorMessage = String.Format(Localization.GetString("OneMustBeChecked.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRequiredFieldValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemRequiredFieldValidator);
               this.HasRequiredValidators = true;
               break;
            case FormItemType.EMailAddress:
               formItemRegExpValidator.ID = validatorID;
               formItemRegExpValidator.ValidationGroup = this.FormValidationGroup;
               formItemRegExpValidator.ControlToValidate = controlToValidate;
               formItemRegExpValidator.CssClass = "NormalRed";
               if (String.IsNullOrEmpty(formItem.ValidationExpression))
                  formItemRegExpValidator.ValidationExpression = Convert.ToString(UserModuleBase.GetSetting(base.PortalId, "Security_EmailValidation"));
               else
                  formItemRegExpValidator.ValidationExpression = validationExpression.ToString();
               formItemRegExpValidator.Required = formItem.FormItemRequired;
               formItemRegExpValidator.RequiredErrorMessage = String.Format(Localization.GetString("ValidEmailIsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRegExpValidator.InvalidErrorMessage = String.Format(Localization.GetString("InvalidEmail.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRegExpValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemRegExpValidator);
               this.HasRequiredValidators = formItem.FormItemRequired;
               break;
            case FormItemType.WebSite:
               formItemRegExpValidator.ID = validatorID;
               formItemRegExpValidator.ValidationGroup = this.FormValidationGroup;
               formItemRegExpValidator.ControlToValidate = String.Format("{0}_TextBox", controlToValidate);
               formItemRegExpValidator.CssClass = "NormalRed";
               if (String.IsNullOrEmpty(formItem.ValidationExpression))
                  formItemRegExpValidator.ValidationExpression = @"^([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
               else
                  formItemRegExpValidator.ValidationExpression = validationExpression.ToString();
               formItemRegExpValidator.Required = formItem.FormItemRequired;
               formItemRegExpValidator.RequiredErrorMessage = String.Format(Localization.GetString("ValidWebSiteIsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRegExpValidator.InvalidErrorMessage = String.Format(Localization.GetString("InvalidWebSite.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRegExpValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemRegExpValidator);
               break;
            case FormItemType.Date:
               formItemDateValidator.ID = validatorID;
               formItemDateValidator.ValidationGroup = this.FormValidationGroup;
               formItemDateValidator.ControlToValidate = String.Format("{0}_DateTextBox", controlToValidate);
               formItemDateValidator.CssClass = "NormalRed";
               formItemDateValidator.Required = formItem.FormItemRequired;
               formItemDateValidator.RequiredErrorMessage = String.Format(Localization.GetString("DateIsRequired.Text", LocalResourceFile), formItem.FormItemLabel, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
               formItemDateValidator.InvalidErrorMessage = String.Format(Localization.GetString("InvalidDate.Text", LocalResourceFile), formItem.FormItemLabel, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
               formItemDateValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemDateValidator);
               break;
            case FormItemType.FileUpload:
               formItemRequiredFieldValidator.ID = validatorID;
               formItemRequiredFieldValidator.ValidationGroup = this.FormValidationGroup;
               formItemRequiredFieldValidator.ControlToValidate = controlToValidate;
               formItemRequiredFieldValidator.CssClass = "NormalRed";
               formItemRequiredFieldValidator.ErrorMessage = String.Format(Localization.GetString("IsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemRequiredFieldValidator.Text = "*";
               this.FormPlaceHolder.Controls.Add(formItemRequiredFieldValidator);
               this.HasRequiredValidators = true;
               break;
            default:
               break;
         }
      }

      protected void CreateFormItemOther(FormItemInfo formItem)
      {
         try
         {
            Panel formItemOtherPanel = new Panel();
            formItemOtherPanel.ID = String.Format("ctl_{0}_otherPanel", formItem.FormItemID);

            TextBox formItemOtherTextBox = new TextBox();
            formItemOtherTextBox.ID = String.Format("ctl_{0}_otherTextBox", formItem.FormItemID);
            formItemOtherTextBox.CssClass = "NormalTextBox";
            formItemOtherTextBox.TabIndex = Convert.ToInt16(formItem.SortValue.Value);
            formItemOtherTextBox.ToolTip = Localization.GetString("SpecifyOther.ToolTip", base.LocalResourceFile);

            if ((formItem.Height != null) && (formItem.Height > 0))
            {
               if (formItem.Height > 1)
               {
                  formItemOtherTextBox.TextMode = TextBoxMode.MultiLine;
                  formItemOtherTextBox.Rows = formItem.Height.Value;
               }
               else
               {
                  formItemOtherTextBox.TextMode = TextBoxMode.SingleLine;
               }
            }
            else
            {
               formItemOtherTextBox.TextMode = TextBoxMode.SingleLine;
            }
            if ((formItem.Width != null) && (formItem.Width.Value > 0))
            {
               formItemOtherTextBox.Width = Unit.Parse(formItem.Width.ToString());
            }

            formItemOtherPanel.Controls.Add(formItemOtherTextBox);

            if (formItem.FormItemRequired)
            {
               RequiredFieldValidator formItemOtherRequiredFieldValidator = new RequiredFieldValidator();
               formItemOtherRequiredFieldValidator.ID = String.Format("val_{0}_forOther", formItem.FormItemID);
               formItemOtherRequiredFieldValidator.ValidationGroup = this.FormValidationGroup;
               formItemOtherRequiredFieldValidator.ControlToValidate = formItemOtherTextBox.ID;
               formItemOtherRequiredFieldValidator.CssClass = "NormalRed";
               formItemOtherRequiredFieldValidator.ErrorMessage = String.Format(Localization.GetString("OtherIsRequired.Text", LocalResourceFile), formItem.FormItemLabel);
               formItemOtherRequiredFieldValidator.Text = "*";
               formItemOtherPanel.Controls.Add(formItemOtherRequiredFieldValidator);
               this.HasRequiredValidators = true;
            }

            switch (formItem.FormItemType)
            {
               case FormItemType.DropDownList:
                  DropDownList formItemDropDownList = (DropDownList)base.FindControl(String.Format("ctl_{0}", formItem.FormItemID));
                  formItemOtherPanel.Visible = (formItemDropDownList.SelectedValue == String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID));
                  break;
               case FormItemType.MultipleSelect:
                  CheckBoxList formItemCheckBoxList = (CheckBoxList)base.FindControl(String.Format("ctl_{0}", formItem.FormItemID));
                  formItemOtherPanel.Visible = ((formItemCheckBoxList.Items[formItemCheckBoxList.Items.Count - 1].Value == String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID)) && (formItemCheckBoxList.Items[formItemCheckBoxList.Items.Count - 1].Selected));
                  break;
               case FormItemType.RadioButtonList:
                  RadioButtonList formItemRadioButtonList = (RadioButtonList)base.FindControl(String.Format("ctl_{0}", formItem.FormItemID));
                  formItemOtherPanel.Visible = (formItemRadioButtonList.SelectedValue == String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID));
                  break;
               default:
                  break;
            }

            this.FormPlaceHolder.Controls.Add(formItemOtherPanel);
         }
         catch (Exception ex)
         {
            Label exceptionLabel = new Label();
            exceptionLabel.Text =
                String.Format(Localization.GetString("ItemCreationException.Text", base.LocalResourceFile),
                    (String.IsNullOrEmpty(formItem.FormItemLabel) ? "?" : formItem.FormItemLabel),
                    Localization.GetString(String.Format("FormItemType.{0}", Enum.GetNames(typeof(FormItemType))[Convert.ToInt32(formItem.FormItemType) - 1]), this.SharedResourceFile),
                 ex.Message);
            this.FormPlaceHolder.Controls.Add(exceptionLabel);
            formItem.FormItemRequired = false;
            formItem.ValidationExpression = String.Empty;
            Exceptions.LogException(ex);
         }
      }

      protected void FormItemDropDownList_SelectedIndexChanged(object sender, EventArgs e)
      {
         DropDownList formItemDropDownList = (DropDownList)sender;
         int formItemDropDownListID = Convert.ToInt32(formItemDropDownList.ID.Substring(4));
         Panel formItemOtherPanel = (Panel)base.FindControl(String.Format("{0}_otherPanel", formItemDropDownList.ID));
         formItemOtherPanel.Visible = (formItemDropDownList.SelectedValue == String.Format("OTHER_FOR_CONTROL_{0}", formItemDropDownListID));
      }

      protected void FormItemCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
      {
         CheckBoxList formItemCheckBoxList = (CheckBoxList)sender;
         int formItemCheckBoxListID = Convert.ToInt32(formItemCheckBoxList.ID.Substring(4));
         Panel formItemOtherPanel = (Panel)base.FindControl(String.Format("{0}_otherPanel", formItemCheckBoxList.ID));
         formItemOtherPanel.Visible = ((formItemCheckBoxList.Items[formItemCheckBoxList.Items.Count - 1].Value == String.Format("OTHER_FOR_CONTROL_{0}", formItemCheckBoxListID)) && (formItemCheckBoxList.Items[formItemCheckBoxList.Items.Count - 1].Selected));
      }

      protected void FormItemRadioButtonList_SelectedIndexChanged(object sender, EventArgs e)
      {
         RadioButtonList formItemRadioButtonList = (RadioButtonList)sender;
         int formItemDropDownListID = Convert.ToInt32(formItemRadioButtonList.ID.Substring(4));
         Panel formItemOtherPanel = (Panel)base.FindControl(String.Format("{0}_otherPanel", formItemRadioButtonList.ID));
         formItemOtherPanel.Visible = (formItemRadioButtonList.SelectedValue == String.Format("OTHER_FOR_CONTROL_{0}", formItemDropDownListID));
      }

      private LiteralControl GetRequiredImage(FormItemInfo formItem)
      {
         LiteralControl requiredImage = new LiteralControl();
         if (formItem.FormItemRequired)
         {
            switch (this.RequiredFieldMarker)
            {
               case RequiredFieldMarkerType.StandardIcon:
                  requiredImage.Text = String.Format("<a href=\"#\" title=\"{0}\"><img src=\"{1}\" alt=\"{0}\" class=\"RequiredImageStyle\" /></a>", Localization.GetString("Required.Text", LocalResourceFile), ResolveUrl("~/images/required.gif"));
                  break;
               case RequiredFieldMarkerType.Asterisk:
                  requiredImage.Text = String.Format("<a style=\"text-decoration: none;\" href=\"#\" title=\"{0}\">*</a>", Localization.GetString("Required.Text", LocalResourceFile));
                  break;
               default:
                  break;
            }
         }
         return requiredImage;
      }

      private Dictionary<string, string> LocalizedDataSource(BabelFishInfo aquarium)
      {
         return this.LocalizedDataSource(aquarium, -1, false);
      }

      private Dictionary<string, string> LocalizedDataSource(BabelFishInfo aquarium, int formItemID, bool includeOther)
      {
         string[] keys = aquarium.FallBack.Split(new string[] { "\n", ";" }, StringSplitOptions.RemoveEmptyEntries);
         string[] values = aquarium.DisplayValue.Split(new string[] { "\n", ";" }, StringSplitOptions.RemoveEmptyEntries);

         Dictionary<string, string> result = new Dictionary<string, string>();
         for (int i = 0; i < keys.Length; i++)
         {
            if (values.Length > i - 1)
               result.Add(keys[i], values[i]);
            else
               result.Add(keys[i], keys[i]);
         }
         if (values.Length > keys.Length)
         {
            for (int i = keys.Length; i < values.Length; i++)
               result.Add(values[i], values[i]);
         }

         if (includeOther)
         {
            result.Add(String.Format("OTHER_FOR_CONTROL_{0}", formItemID), Localization.GetString("Other", this.SharedResourceFile));
         }


         return result;
      }
#endregion

#region Submission Methods
      private string CreateFormSubmissionXML()
      {
         // temporary string for selected and other value(s)
         StringBuilder formItemSelectedValue = new StringBuilder(String.Empty);
         StringBuilder formItemOtherValue = new StringBuilder(String.Empty);
         // Web controls
         TextBox formItemTextBox;
         DropDownList formItemDropDownList;
         RadioButtonList formItemRadioButtonList;
         CheckBoxList formItemCheckBoxList;
         TextBox formItemOtherTextBox = null;
         CheckBox formItemCheckBox;
         FileUpload formItemFileUpload;
         Label formItemHidden;
         PortalSecurity security = new PortalSecurity();

         // Create the XML String to store the submissions
         StringBuilder submission = new StringBuilder("");

         // Iterate Form items to get the values...
         submission.Append("<formSubmission>");

         foreach (FormItemInfo formItem in this.TheForm)
         {
            string formItemID = String.Format("ctl_{0}", formItem.FormItemID);
            switch (formItem.FormItemType)
            {
               case FormItemType.TextBox:
                  formItemTextBox = (TextBox)this.FindControl(formItemID);
                  formItemTextBox.Text = formItemTextBox.Text.Trim();
                  formItemTextBox.Text = security.InputFilter(formItemTextBox.Text, PortalSecurity.FilterFlag.NoScripting).Trim();
                  formItemTextBox.Text = HtmlUtils.StripTags(formItemTextBox.Text, false);
                  formItemSelectedValue.Append(Server.HtmlEncode(formItemTextBox.Text));
                  break;
               case FormItemType.TextArea:
                  formItemTextBox = (TextBox)this.FindControl(formItemID);
                  formItemTextBox.Text = formItemTextBox.Text.Trim();
                  formItemTextBox.Text = security.InputFilter(formItemTextBox.Text, PortalSecurity.FilterFlag.NoScripting).Trim();
                  formItemTextBox.Text = HtmlUtils.StripTags(formItemTextBox.Text, false);
                  formItemSelectedValue.Append(Server.HtmlEncode(security.InputFilter(formItemTextBox.Text, PortalSecurity.FilterFlag.MultiLine).Trim()));
                  break;
               case FormItemType.DropDownList:
                  formItemDropDownList = (DropDownList)this.FindControl(formItemID);
                  if ((formItem.FormItemOther) && (formItemDropDownList.SelectedValue == String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID)))
                  {
                     formItemSelectedValue.Append(formItemDropDownList.SelectedValue);
                     string formItemOtherID = String.Format("ctl_{0}_otherTextBox", formItem.FormItemID);
                     formItemOtherTextBox = (TextBox)this.FindControl(formItemOtherID);
                     formItemOtherTextBox.Text = formItemOtherTextBox.Text.Trim();
                     formItemOtherTextBox.Text = security.InputFilter(formItemOtherTextBox.Text, PortalSecurity.FilterFlag.NoScripting).Trim();
                     formItemOtherTextBox.Text = HtmlUtils.StripTags(formItemOtherTextBox.Text, false);
                     formItemOtherValue.Append(Server.HtmlEncode(formItemOtherTextBox.Text));
                  }
                  else
                     formItemSelectedValue.Append(formItemDropDownList.SelectedItem.Text);
                  break;
               case FormItemType.MultipleSelect:
                  formItemCheckBoxList = (CheckBoxList)this.FindControl(formItemID);
                  for (int j = 0; j < formItemCheckBoxList.Items.Count; j++)
                  {
                     if (formItemCheckBoxList.Items[j].Selected)
                     {
                        if ((formItem.FormItemOther) && (formItemCheckBoxList.Items[j].Value == String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID)))
                        {
                           formItemSelectedValue.Append(String.Format("{0};", formItemCheckBoxList.Items[j].Value));
                           string formItemOtherID = String.Format("ctl_{0}_otherTextBox", formItem.FormItemID);
                           formItemOtherTextBox = (TextBox)this.FindControl(formItemOtherID);
                           formItemOtherTextBox.Text = formItemOtherTextBox.Text.Trim();
                           formItemOtherTextBox.Text = security.InputFilter(formItemOtherTextBox.Text, PortalSecurity.FilterFlag.NoScripting).Trim();
                           formItemOtherTextBox.Text = HtmlUtils.StripTags(formItemOtherTextBox.Text, false);
                           formItemOtherValue.Append(Server.HtmlEncode(formItemOtherTextBox.Text));
                        }
                        else
                           formItemSelectedValue.Append(String.Format("{0};", formItemCheckBoxList.Items[j].Text));
                     }
                  }
                  if (formItemSelectedValue.Length > 0)
                     formItemSelectedValue.Remove(formItemSelectedValue.Length - 1, 1);
                  break;
               case FormItemType.Checkbox:
                  formItemCheckBox = (CheckBox)this.FindControl(formItemID);
                  formItemSelectedValue.Append(formItemCheckBox.Checked.ToString());
                  break;
               case FormItemType.RadioButtonList:
                  formItemRadioButtonList = (RadioButtonList)this.FindControl(formItemID);
                  if (formItemRadioButtonList.SelectedItem != null)
                  {
                     if ((formItem.FormItemOther) && (formItemRadioButtonList.SelectedValue == String.Format("OTHER_FOR_CONTROL_{0}", formItem.FormItemID)))
                     {
                        formItemSelectedValue.Append(formItemRadioButtonList.SelectedValue);
                        string formItemOtherID = String.Format("ctl_{0}_otherTextBox", formItem.FormItemID);
                        formItemOtherTextBox = (TextBox)this.FindControl(formItemOtherID);
                        formItemOtherTextBox.Text = formItemOtherTextBox.Text.Trim();
                        formItemOtherTextBox.Text =
                           security.InputFilter(formItemOtherTextBox.Text, PortalSecurity.FilterFlag.NoScripting).Trim();
                        formItemOtherTextBox.Text = HtmlUtils.StripTags(formItemOtherTextBox.Text, false);
                        formItemOtherValue.Append(Server.HtmlEncode(formItemOtherTextBox.Text));
                     }
                     else
                        formItemSelectedValue.Append(formItemRadioButtonList.SelectedItem.Text);
                  }
                  break;
               case FormItemType.EMailAddress:
                  formItemTextBox = (TextBox)this.FindControl(formItemID);
                  formItemSelectedValue.Append(formItemTextBox.Text.Trim());
                  break;
               case FormItemType.WebSite:
                  formItemDropDownList = (DropDownList)this.FindControl(String.Format("{0}_DropDownList", formItemID));
                  formItemTextBox = (TextBox)this.FindControl(String.Format("{0}_TextBox", formItemID));
                  if (!(string.IsNullOrEmpty(formItemTextBox.Text.Trim())))
                  {
                     formItemSelectedValue.Append(formItemDropDownList.SelectedItem.Text);
                     formItemSelectedValue.Append(formItemTextBox.Text);
                  }
                  break;
               case FormItemType.Date:
                  formItemTextBox = (TextBox)this.FindControl(String.Format("{0}_DateTextBox", formItemID));
                  if (!(string.IsNullOrEmpty(formItemTextBox.Text)))
                  {
                     if (!(string.IsNullOrEmpty(formItemTextBox.Text)))
                     {
                        try
                        {
                           DateTime formItemDateValue = DateTime.Parse(formItemTextBox.Text);
                           formItemSelectedValue.Append(formItemDateValue.ToBinary().ToString());
                        }
                        catch { }
                     }
                  }
                  break;
               case FormItemType.SendTo:
                  formItemDropDownList = (DropDownList)this.FindControl(formItemID);
                  formItemSelectedValue.Append(formItemDropDownList.SelectedItem.Text);
                  formItemSelectedValue.Append(" [");
                  formItemSelectedValue.Append(formItemDropDownList.SelectedItem.Value);
                  formItemSelectedValue.Append("]");
                  break;
               case FormItemType.FileUpload:
                  formItemFileUpload = (FileUpload)this.FindControl(formItemID);
                  if (formItemFileUpload.HasFile)
                  {

                     string fileExtension = Path.GetExtension(formItemFileUpload.FileName).ToLower().Replace(".", String.Empty);
                     string allowedExtensions;
                     if (!(this.HostSettings.TryGetValue("FileExtensions", out allowedExtensions)))
                        allowedExtensions = String.Empty;

                     if ((!(String.IsNullOrEmpty(allowedExtensions))) && (allowedExtensions.ToLower().IndexOf(fileExtension) < 0))
                     {
                        return (String.Format("[ERROR]RestrictedFileType;{0}", formItemFileUpload.FileName));
                     }
                     else
                     {
                        string uniqueFileName = String.Format("{0}.{1}", Guid.NewGuid(), fileExtension);
                        try
                        {
                           string uploadResult = FileSystemUtils.UploadFile(this.UploadFolder, formItemFileUpload.PostedFile, uniqueFileName, false);
                           if (String.IsNullOrEmpty(uploadResult))
                           {
                              formItemSelectedValue.Append(uniqueFileName);
                              this.UploadedFiles.Add(uniqueFileName, formItemFileUpload.FileName);
                           }
                           else
                           {
                              throw new Exception(uploadResult);
                           }
                        }
                        catch (Exception ex)
                        {
                           return (String.Format("[ERROR]{0}", ex.Message));
                        }
                     }
                  }
                  break;
               case FormItemType.SendCopy:
                  if (!(this.HideSendCopy))
                  {
                     formItemCheckBox = (CheckBox)this.FindControl(formItemID);
                     formItemSelectedValue.Append(formItemCheckBox.Checked.ToString());
                     this.sendCopy = formItemCheckBox.Checked;
                  }
                  else
                  {
                     formItemSelectedValue.Append("false");
                  }
                  break;
               case FormItemType.Hidden:
                  formItemHidden = (Label)this.FindControl(formItemID);
                  formItemSelectedValue.Append(Server.HtmlEncode(formItemHidden.Text));
                  break;
               default:
                  break;
            }
            // Create the XML String
            submission.Append("<formItem>");
            // FormItemType cannot be Null
            submission.Append("<formItemType>");
            submission.Append(Convert.ToInt32(formItem.FormItemType));
            submission.Append("</formItemType>");
            // FormItemValue
            submission.Append("<formItemValue><![CDATA[");
            submission.Append(formItem.FormItemValue);
            submission.Append("]]></formItemValue>");
            // FormItemSelectedValue(s)
            submission.Append("<formItemSelectedValue><![CDATA[");
            submission.Append(formItemSelectedValue);
            submission.Append("]]></formItemSelectedValue>");
            if (formItem.FormItemType == FormItemType.FileUpload)
            {
               string s;
               if (this.UploadedFiles.TryGetValue(formItemSelectedValue.ToString(), out s))
               {
                  submission.Append("<formItemOriginalFileName><![CDATA[");
                  submission.Append(s);
                  submission.Append("]]></formItemOriginalFileName>");
               }
            }
            // Label
            BabelFishInfo fish = this.BabelFishController.GetString(base.PortalId, base.PortalSettings.DefaultLanguage, String.Format("helferlein.Form.FormItem.{0}", formItem.FormItemID), "FormItemLabel");
            if (fish != null)
            {
               submission.Append("<formItemLabel><![CDATA[");
               submission.Append(fish.StringText);
               submission.Append("]]></formItemLabel>");
            }
            else
               submission.Append("<formItemLabel />");
            // Repeat Columns
            if (formItem.FormItemRepeatColumns.HasValue)
            {
               submission.Append("<formItemRepeatColumns>");
               submission.Append(formItem.FormItemRepeatColumns);
               submission.Append("</formItemRepeatColumns>");
            }
            else
               submission.Append("<formItemRepeatColumns />");
            // Sort Value cannot be Null
            submission.Append("<formItemSortValue>");
            submission.Append(formItem.SortValue);
            submission.Append("</formItemSortValue>");
            // Required.ToString() is either "True" or "False"
            submission.Append("<formItemRequired>");
            submission.Append(formItem.FormItemRequired);
            submission.Append("</formItemRequired>");
            // Width
            if (formItem.Width.HasValue)
            {
               submission.Append("<formItemWidth>");
               submission.Append(formItem.Width);
               submission.Append("</formItemWidth>");
            }
            else
               submission.Append("<formItemWidth />");
            // Height
            if (formItem.Height.HasValue)
            {
               submission.Append("<formItemHeight>");
               submission.Append(formItem.Height);
               submission.Append("</formItemHeight>");
            }
            else
               submission.Append("<formItemHeight />");
            // Link Target
            if (formItem.FormItemType == FormItemType.WebSite)
            {
               if (formItem.FormItemLinkTarget == LinkTarget.None)
                  submission.Append("<formItemLinkTarget />");
               else
               {
                  submission.Append("<formItemLinkTarget>");
                  submission.Append((int)formItem.FormItemLinkTarget);
                  submission.Append("</formItemLinkTarget>");
               }
            }
            else
            {
               submission.Append("<formItemLinkTarget />");
            }
            // Validation Expression
            if (!(String.IsNullOrEmpty(formItem.ValidationExpression)))
            {
               submission.Append("<formItemValidationExpression><![CDATA[");
               submission.Append(formItem.ValidationExpression);
               submission.Append("]]></formItemValidationExpression>");
            }
            else
               submission.Append("<formItemValidationExpression />");
            // FormItem Other
            submission.Append("<formItemOther>");
            submission.Append(formItem.FormItemOther);
            submission.Append("</formItemOther>");
            if ((formItem.FormItemOther) && (formItemOtherValue.Length > 0))
            {
               submission.Append("<formItemOtherValue><![CDATA[");
               submission.Append(formItemOtherValue);
               submission.Append("]]></formItemOtherValue>");
            }
            else
               submission.Append("<formItemOtherValue />");
            // Help Text
            submission.Append("<formItemHelpText><![CDATA[");
            submission.Append(formItem.FormItemHelpText);
            submission.Append("]]></formItemHelpText>");
            // FormItemTemplate
            if (!(String.IsNullOrEmpty(formItem.FormItemTemplate)))
            {
               submission.Append("<formItemTemplate><![CDATA[");
               submission.Append(formItem.FormItemTemplate);
               submission.Append("]]></formItemTemplate>");
            }
            else
            {
               submission.Append("<formItemTemplate />");
            }
            // End Tag
            submission.Append("</formItem>");
            // Clear the temporary string for selected value(s)
            formItemSelectedValue.Remove(0, formItemSelectedValue.Length);
            // <!-- Code provided by user Lode_Leroy on CodePlex
            formItemOtherValue.Remove(0, formItemOtherValue.Length);
            // Code provided by user Lode_Leroy on CodePlex -->
         }
         // Closing XML Tag
         submission.Append("</formSubmission>");
         return submission.ToString();
      }

      private bool SendEmail(FormSubmissionInfo fsi)
      {
         bool sendError = false;

         try
         {
            StringBuilder emailBody = new StringBuilder("");
            MailFormat mailFormat = MailFormat.Text;
            if (this.EMailFormat == MailFormat.Html)
            {
               mailFormat = MailFormat.Html;
               emailBody.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
               emailBody.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>");
               emailBody.Append("<style type=\"text/css\">");
               StringBuilder styleSheet = new StringBuilder("");
               // Try to append original stylesheet file
               string mailStyleSheet = String.Format("{0}Mail.css", Server.MapPath(base.ControlPath));
               if (File.Exists(mailStyleSheet))
               {
                  using (StreamReader sr = File.OpenText(mailStyleSheet))
                  {
                     String line;
                     while ((line = sr.ReadLine()) != null)
                        styleSheet.Append(line);
                     sr.Close();
                  }
               }
               // or provide some default style sheet
               else
               {
                  styleSheet.Append(".Body { font-family: Arial, Helvetica, sans-serif; font-size: 80%; color: Black; } ");
                  styleSheet.Append(".Normal { } ");
                  styleSheet.Append(".NormalBold { font-weight: bold; }");
               }
               emailBody.Append(styleSheet.ToString());
               emailBody.Append("</style></head><body class=\"Body\">");
               emailBody.Append(fsi.ToHtml(false, false, true, true, this.IncludeIPAddressInEmail));
               emailBody.Append("</body></html>");
            }
            else
            {
               emailBody.Append(fsi.ToText(true, this.IncludeIPAddressInEmail));
            }

            string senderAddress;
            if (String.IsNullOrEmpty(this.SenderAddress))
               senderAddress = PortalSettings.Email;
            else
            {
               if (this.SenderAddress == "[ADMIN]")
                  senderAddress = PortalSettings.Email;
               else if (this.SenderAddress == "[HOST]")
                  // senderAddress = PortalSettings.HostSettings["HostEmail"].ToString();
                  // senderAddress = Host.GetHostSettingsDictionary()["HostEmail"];
                  senderAddress = HostController.Instance.GetSettingsDictionary()["HostEmail"];
               else if (this.SenderAddress.StartsWith("[USERID]"))
               {
                  UserController uc = new UserController();
                  UserInfo ui = uc.GetUser(base.PortalId, Convert.ToInt32(this.SenderAddress.Substring(8)));
                  senderAddress = String.Format("{0}<{1}>", ui.DisplayName.Replace("\"", ""), ui.Email);
               }
               else
               {
                  senderAddress = PortalSettings.Email;
                  TextBox senderTextBox = (TextBox)this.FindControl(String.Format("ctl_{0}", this.SenderAddress.Substring(10)));
                  if (senderTextBox != null)
                     senderAddress = senderTextBox.Text;
               }
            }

            string replyToAddress;
            if (String.IsNullOrEmpty(this.ReplyToAddress))
               replyToAddress = PortalSettings.Email;
            else
            {
               if (this.ReplyToAddress == "[ADMIN]")
                  replyToAddress = PortalSettings.Email;
               else if (this.ReplyToAddress == "[HOST]")
                  // replyToAddress = PortalSettings.HostSettings["HostEmail"].ToString();
                  // replyToAddress = Host.GetHostSettingsDictionary()["HostEmail"];
                  replyToAddress = HostController.Instance.GetSettingsDictionary()["HostEmail"];
               else if (this.ReplyToAddress.StartsWith("[USERID]"))
               {
                  UserController uc = new UserController();
                  UserInfo ui = uc.GetUser(base.PortalId, Convert.ToInt32(this.ReplyToAddress.Substring(8)));
                  replyToAddress = String.Format("{0}<{1}>", ui.DisplayName.Replace("\"", ""), ui.Email);
               }
               else
               {
                  replyToAddress = PortalSettings.Email;
                  TextBox replyToTextBox = (TextBox)this.FindControl(String.Format("ctl_{0}", this.ReplyToAddress.Substring(10)));
                  if (replyToTextBox != null)
                     replyToAddress = replyToTextBox.Text;
               }
            }

            // Send To
            string recipient = String.Empty;
            if (String.IsNullOrEmpty(fsi.RecipientAddressValue))
               recipient = this.EMailAddress;
            else
               recipient = fsi.RecipientAddressValue.Replace('[', '<').Replace(']', '>');

            string eMailSubject;
            if (this.UseHeadlineAsSubject)
            {
               eMailSubject = fsi.HeadlineValue;
            }
            else
            {
               BabelFishInfo subject = this.BabelFishController.GetString(base.PortalId, CultureInfo.CurrentCulture.Name, String.Format("helferlein.Form.Settings.{0}", base.ModuleId), "Subject");
               if (subject == null)
                  eMailSubject = String.Format(Localization.GetString("EMailSubject.Text", base.LocalResourceFile), ModuleConfiguration.ModuleTitle, PortalSettings.PortalName);
               else
               {
                  try
                  {
                     string s = subject.DisplayValue;
                     s = s.Replace("[PORTAL_NAME]", base.PortalSettings.PortalName);
                     s = s.Replace("[PORTAL_ID]", base.PortalId.ToString());
                     s = s.Replace("[TAB_NAME]", new TabController().GetTab(base.TabId, base.PortalId, true).TabName);
                     s = s.Replace("[TAB_ID]", base.TabId.ToString());
                     s = s.Replace("[MODULE_TITLE]", base.ModuleConfiguration.ModuleTitle);
                     s = s.Replace("[MODULE_ID]", base.ModuleId.ToString());
                     eMailSubject = s;
                  }
                  catch { eMailSubject = String.Format(Localization.GetString("EMailSubject.Text", base.LocalResourceFile), ModuleConfiguration.ModuleTitle, PortalSettings.PortalName); }
               }
            }


            string[] attachments = new string[this.UploadedFiles.Count];
            this.UploadedFiles.Keys.CopyTo(attachments, 0);
            for (int i = 0; i < this.UploadedFiles.Count; i++)
            {
               attachments[i] = String.Format("{0}\\{1}", this.UploadFolder, attachments[i]);
            }

            // string smtpServer = PortalSettings.HostSettings["SMTPServer"].ToString();
            string smtpServer;
            if (!(this.HostSettings.TryGetValue("SMTPServer", out smtpServer)))
               smtpServer = String.Empty;
            // string smtpAuthentication = PortalSettings.HostSettings["SMTPAuthentication"].ToString()
            string smtpAuthentication;
            if (!(this.HostSettings.TryGetValue("SMTPAuthentication", out smtpAuthentication)))
               smtpAuthentication = String.Empty;
            // string smtpUsername = PortalSettings.HostSettings["SMTPUsername"].ToString();
            string smtpUsername;
            if (!(this.HostSettings.TryGetValue("SMTPUserName", out smtpUsername)))
               smtpUsername = String.Empty;
            // string smtpPassword = PortalSettings.HostSettings["SMTPPassword"].ToString();
            string smtpPassword;
            if (!(this.HostSettings.TryGetValue("SMTPPassword", out smtpPassword)))
               smtpPassword = String.Empty;
            // string smtpEnableSSL = PortalSettings.HostSettings["SMTPEnableSSL"].ToString();
            string smtpEnableSSL;
            if (!(this.HostSettings.TryGetValue("SMTPEnableSSL", out smtpEnableSSL)))
               smtpEnableSSL = "N";

            sendError = (!(String.IsNullOrEmpty(Mail.SendMail(senderAddress,
                                                             recipient,
                                                             String.Empty,
                                                             String.Empty,
                                                             replyToAddress,         // REPLY-TO
                                                             MailPriority.Normal,
                                                             eMailSubject,
                                                             mailFormat,
                                                             Encoding.UTF8,
                                                             emailBody.ToString(),
                                                             attachments,
                                                             smtpServer,
                                                             smtpAuthentication,
                                                             smtpUsername,
                                                             smtpPassword,
                                                             (smtpEnableSSL == "Y")))));
            if ((!(sendError)) && (this.sendCopy))
            {
               emailBody.Remove(0, emailBody.Length);
               if (mailFormat == MailFormat.Html)
               {
                  emailBody.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                  emailBody.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>");
                  emailBody.Append("<style type=\"text/css\">");
                  StringBuilder styleSheet = new StringBuilder("");
                  // Try to append original stylesheet file
                  string mailStyleSheet = String.Format("{0}Mail.css", Server.MapPath(base.ControlPath));
                  if (File.Exists(mailStyleSheet))
                  {
                     using (StreamReader sr = File.OpenText(mailStyleSheet))
                     {
                        String line;
                        while ((line = sr.ReadLine()) != null)
                           styleSheet.Append(line);
                        sr.Close();
                     }
                  }
                  // or provide some default style sheet
                  else
                  {
                     styleSheet.Append(".Body { font-family: Arial, Helvetica, sans-serif; font-size: 80%; color: Black; } ");
                     styleSheet.Append(".Normal { } ");
                     styleSheet.Append(".NormalBold { font-weight: bold; }");
                  }
                  emailBody.Append(styleSheet.ToString());
                  emailBody.Append("</style></head><body class=\"Body\">");
                  emailBody.Append(fsi.ToHtml(false, false, true, true, this.IncludeIPAddressInEmail));
                  emailBody.Append("</body></html>");
               }
               else
               {
                  emailBody.Append(fsi.ToText(false, this.IncludeIPAddressInEmail));
               }
               sendError = (!(String.IsNullOrEmpty(Mail.SendMail(recipient,
                                                                senderAddress,
                                                                String.Empty,
                                                                String.Empty,
                                                                replyToAddress,         // REPLY-TO
                                                                MailPriority.Normal,
                                                                eMailSubject,
                                                                mailFormat,
                                                                Encoding.UTF8,
                                                                emailBody.ToString(),
                                                                attachments,
                                                                smtpServer,
                                                                smtpAuthentication,
                                                                smtpUsername,
                                                                smtpPassword,
                                                                (smtpEnableSSL == "Y")))));
            }

         }
         catch (Exception ex)
         {
            Exceptions.LogException(ex);
            sendError = true;
         }
         return sendError;
      }
#endregion

#region Submission Display
      private Label ApprovedSubmissionsLabel()
      {
         // Show the approved submissions within a given number of days above or below the form
         Label showApprovedSubmissions = new Label();
         StringBuilder showApprovedSubmissionsText = new StringBuilder();
         if (this.FormSubmissions.Count > 0)
         {
            string currentGroupLabel = string.Empty;

            foreach (FormSubmissionInfo formSubmission in this.FormSubmissions)
            {
               if (currentGroupLabel != formSubmission.GroupItemValue)
               {
                  currentGroupLabel = formSubmission.GroupItemValue;
                  showApprovedSubmissionsText.Append("<span class=\"Head\">");
                  showApprovedSubmissionsText.Append(currentGroupLabel);
                  showApprovedSubmissionsText.Append("</span><br /><hr />");
               }
               if ((!(String.IsNullOrEmpty(formSubmission.FormSubmissionLocale))) && (this.ShowFlag))
               {
                  showApprovedSubmissionsText.Append("<img src=\"");
                  showApprovedSubmissionsText.Append(Page.ResolveClientUrl("~/images/flags/"));
                  showApprovedSubmissionsText.Append(formSubmission.FormSubmissionLocale);
                  showApprovedSubmissionsText.Append(".gif\" border=\"0\"><br />");
               }
               if (this.ShowDate)
                  showApprovedSubmissions.Text += String.Format("<span class=\"NormalBold\">{0:D}</span><br />", formSubmission.FormSubmissionDate);
               if (!(String.IsNullOrEmpty(this.RenderAsHeadline)))
               {
                  showApprovedSubmissions.Text += "<div class=\"Head\" width=\"100%\"";
                  if (!(String.IsNullOrEmpty(this.HeadlineAlignment)))
                     showApprovedSubmissions.Text += String.Format(" align=\"{0}\"", this.HeadlineAlignment);
                  showApprovedSubmissions.Text += String.Format(">{0}</div>", formSubmission.HeadlineValue);
               }
               showApprovedSubmissions.Text += String.Format("{0}<hr />", formSubmission.ToHtml());
            }
         }
         return showApprovedSubmissions;
      }
#endregion

#region Theme
      private void SetTheme()
      {
         HtmlLink cssLink = new HtmlLink();
         string themeName = this.Theme.Substring(0, this.Theme.Length - 4);
         if (this.Theme.EndsWith(" [M]"))
         {
            if (File.Exists(String.Format("{0}Themes\\{1}\\{1}.css", Server.MapPath(base.ControlPath), themeName)))
               cssLink.Href = String.Format("{0}Themes/{1}/{1}.css", base.ControlPath, themeName);
         }
         else
         {
            if (File.Exists(String.Format("{0}helferlein\\helferlein_Form\\Themes\\{1}\\{1}.css", this.CurrentPortalSettings.HomeDirectoryMapPath, themeName)))
               cssLink.Href = String.Format("{0}helferlein/helferlein_Form/Themes/{1}/{1}.css", this.CurrentPortalSettings.HomeDirectory, themeName);
         }

         if (String.IsNullOrEmpty(cssLink.Href))
            cssLink.Href = String.Format("{0}Themes/Default/Default.css", base.ControlPath);

         cssLink.Attributes.Add("rel", "stylesheet");
         cssLink.Attributes.Add("type", "text/css");
         this.Page.Header.Controls.Add(cssLink);
      }
#endregion
   }
}

